package com.stylefeng.guns.modular.huamao.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.IAccountService;
import com.stylefeng.guns.modular.huamao.service.ISktOrdersStoresService;
import com.stylefeng.guns.modular.huamao.service.ISktShopsService;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 线下商家订单表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-04-24
 */
@Service
public class SktOrdersStoresServiceImpl extends ServiceImpl<SktOrdersStoresMapper, SktOrdersStores> implements ISktOrdersStoresService {

	@Autowired
	private SktOrdersStoresMapper sktOrdersStoresMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private LogScoreMapper logScoreMapper;
	@Autowired
	private AccountShopMapper accountShopMapper;
	@Autowired
	private LogStockscoreMapper logStockscoreMapper;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private ISktShopsService sktShopsService;
	@Autowired
	private SktShopsMapper sktShopsMapper;
    @Autowired
    private SktSysConfigsMapper  sysConfigsMapper;
    @Autowired
	private SktSysConfigsMapper sktSysConfigsMapper;


	@Override
	public List<SktOrdersStoresDto> showOrdersStoresInfo(SktOrdersStoresDto sktOrdersStoresDto) {
		List<SktOrdersStoresDto> list = sktOrdersStoresMapper.showOrdersStoresInfo(sktOrdersStoresDto);
		return list;
	}
	@Override
	public int selectCount() {
		// TODO Auto-generated method stub
		return sktOrdersStoresMapper.selectCount();
	}
	@Override
	public int selectOrdersStoresTotal() {
		// TODO Auto-generated method stub
		return sktOrdersStoresMapper.selectOrdersStoresTotal();
	}

    @Override
    public List<Map<String, Object>> selectUserOrdersStores(SktOrdersStoresDto sktOrdersStoresDto) {
		List<Map<String, Object>> list  = sktOrdersStoresMapper.selectUserOrdersStores(sktOrdersStoresDto);
		return list;
    }
	@Override
	public List<Map<String, Object>> selectShopOrdersStoresUp(SktOrdersStoresDto sktOrdersStoresDto) {
		List<Map<String, Object>> list = sktOrdersStoresMapper.selectShopOrdersStoresUp(sktOrdersStoresDto);
		return list;
	}
	@Override
	public List<Map<String, Object>> selectShopOrdersStoresCh(SktOrdersStoresDto sktOrdersStoresDto) {
		List<Map<String, Object>> list = sktOrdersStoresMapper.selectShopOrdersStoresCh(sktOrdersStoresDto);
		return list;
	}
	@Override
	public List<Map<String, Object>> selectShopOrdersStoresOk(SktOrdersStoresDto sktOrdersStoresDto) {
		List<Map<String, Object>> list = sktOrdersStoresMapper.selectShopOrdersStoresOk(sktOrdersStoresDto);
		return list;
	}
	@Override
	public List<Map<String, Object>> appSelectAllOrders(Map<String,Object> map) {
		return sktOrdersStoresMapper.appSelectAllOrders( map);
	}
@Transactional
	@Override
	public Integer appOrderStoreCancel(String orderNo) {
		try{
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orderNo",orderNo);
			map.put("orderStatus",2);
			map.put("checkTime",new Date());
			Integer update = sktOrdersStoresMapper.appOrderStoreCancel(map);
			SktOrdersStores sktOrdersStores = sktOrdersStoresMapper.appFindOrderStoreById(orderNo);
			Account account=new Account();
			account.setUserId(sktOrdersStores.getUserId());
			EntityWrapper<Account> ew =new EntityWrapper<Account>(account);
			Account account1 = accountService.selectOne(ew);
//      	 SktShops sktShops=new SktShops();
//        sktShops.setUserId(user.getUserId());
//        EntityWrapper<SktShops> entityWrapper=new EntityWrapper<SktShops>(sktShops);
			SktShops sktShops = sktShopsService.selectById(sktOrdersStores.getShopId());
			//支付类型 2 现金账户支付 3开元宝支付
			Integer payType = sktOrdersStores.getPayType();
			if(payType == 2){
				//现金
				BigDecimal cash = sktOrdersStores.getCash();
				accountService.insertLogCash(1,sktShops.getUserId(),sktOrdersStores.getUserId(),sktOrdersStores.getOrderNo(),account1.getCash(),"线下门店消费退款",7,sktOrdersStores.getCash());
				//给客户加现金
				account1.setCash(account1.getCash().add(cash));
			}else if(payType == 3){
				//华宝
				BigDecimal kaiyuan = sktOrdersStores.getKaiyuan();
				//华宝手续费
				BigDecimal kaiyuanFee = sktOrdersStores.getKaiyuanFee();
				// 华宝消费记录
				accountService.insertLogKaiyuan(sktShops.getUserId(), sktOrdersStores.getKaiyuan(), 1, sktOrdersStores.getOrderNo(), account1.getKaiyuan(), "线下商城消费退还", 5, account.getUserId());
				//华宝消费手续费记录
				accountService.insertLogKaiyuan(sktShops.getUserId(), sktOrdersStores.getKaiyuanFee(), 1, sktOrdersStores.getOrderNo(), account1.getKaiyuan(), "消费的手续费和税率退还", 5, account.getUserId());
				account1.setKaiyuan(account1.getKaiyuan().add(kaiyuan).add(kaiyuanFee));
			}
			accountService.updateById(account1);
			return update;
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return  0;
		}

	}

	@Override
	@Transactional
	public Map<String,Object> appOrderStoreConfirm(String orderNo) {
        Map<String,Object> map2 = new HashMap<String,Object>();
        SktOrdersStores sktOrdersStores = sktOrdersStoresMapper.appFindOrderStoreById(orderNo);
        //查询商家实时账户    商家扣除库存积分给用户加积分
        AccountShop accountShop = accountShopMapper.selectByShopId(sktOrdersStores.getShopId());
		BigDecimal payMoney = sktOrdersStores.getTotalMoney();
        Integer shopId = accountShop.getShopId();
        SktShops sktShops = sktShopsMapper.selectById(accountShop.getShopId());
        if(sktOrdersStores.getScore().compareTo(accountShop.getStockScore())==1){
            map2.put("mes","您的库存积分不足以支付本次积分赠送，请及时充值！");
            return map2;
        }else {
            try {
				//商家类型 0个体 1公司
				if(sktShops.getCompanyType() == 0) {
					//个体户每日限额
					SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("gthMRXE");
					String gthMRXE = sktSysConfigs2.getFieldValue();
					Map<String,Object> map3 = new HashMap<String,Object>();
					map3.put("shopId",shopId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String today = sdf.format(new Date());
					map3.put("today",today);
					//查询商家的今日营业额
					BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
					if(todayTurnover != null){
						if(todayTurnover.add(payMoney).compareTo(new BigDecimal(gthMRXE)) == 1){
							map2.put("mes","对不起这笔订单将让您今天限额超过上限！");
							return map2;
						}
					}
				}
				if(sktShops.getCompanyType() == 1){
					//公司每日限额
					SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("qyMRXE");
					String qyMRXE = sktSysConfigs2.getFieldValue();
					Map<String,Object> map3 = new HashMap<String,Object>();
					map3.put("shopId",shopId);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String today = sdf.format(new Date());
					map3.put("today",today);
					//查询商家的今日营业额
					BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map3);
					if(todayTurnover != null){
						if(todayTurnover.add(payMoney).compareTo(new BigDecimal(qyMRXE)) == 1){
							map2.put("mes","对不起这笔订单将让您今天限额超过上限！");
							return map2;
						}
					}
				}
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("orderNo", orderNo);
                map.put("orderStatus", 3);
                map.put("checkTime", new Date());
                Integer update = sktOrdersStoresMapper.appOrderStoreCancel(map);
                if (update != 0) {
                    //赠送积分数量
                    BigDecimal score = sktOrdersStores.getScore();
                    //商家id
                    //Integer shopId = sktOrdersStores.getShopId();
                    SktShops sktShops2 = sktShopsService.selectById(shopId);
                    //shop对应的user
                    Users usersShop = usersService.selectById(sktShops2.getUserId());
                    //消费的用户id
                    Integer userId = sktOrdersStores.getUserId();
                    //消费用户
                    Users users = usersService.selectById(userId);
                    this.insertLogStockScore(4, accountShop.getUserId(), accountShop.getUserId(), sktOrdersStores.getOrderNo(), accountShop.getStockScore(), -1, score, "线下订单发放库存积分");
                    accountShop.setStockScore(accountShop.getStockScore().subtract(score));
                    accountShopMapper.updateById(accountShop);
                    //查询用户实时账户   给用户加积分
                    Account account = accountMapper.findScoreById(userId);
                    this.insertLogScore(0, 2, sktOrdersStores.getOrderNo(), account.getScore(), "线下商家消费获得", score, 1, userId);
                    account.setScore(account.getScore().add(score));
                    account.setTotalScore(account.getTotalScore().add(score));
                    Integer update2 = accountMapper.updateById(account);
                    //上线消费奖励
                    if (users.getInviteId() != 0) {
                        accountService.saleAward(users.getInviteId(), score, userId, orderNo);
                    }
                    // 销售奖
                    if (usersShop.getInviteId() != 0) {
                        accountService.marketAward(usersShop.getInviteId(), score, usersShop.getUserId(), orderNo);
                    }
                    //特别奖励
                    //特别消费奖励
                    List<Integer> ids = usersService.getIds(userId);
                    if (ids != null && ids.size() > 0) {
                        SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("consumeProfit");
                        String fieldValue = sysConfig.getFieldValue();
                        BigDecimal percent = new BigDecimal(fieldValue).divide(new BigDecimal(100));
                        accountService.specialAward(ids, percent, score, 1, users.getInviteId(), orderNo);
                    }
                    //特别销售
                    Integer inviteId = usersShop.getInviteId();
                    List<Integer> idss = usersService.getIds(usersShop.getUserId());
                    if (idss != null && idss.size() > 0) {
                        SktSysConfigs sysConfig = sysConfigsMapper.selectSysConfigsByFieldCode("turnoverProfit");
                        String fieldValue = sysConfig.getFieldValue();
                        BigDecimal percent = new BigDecimal(fieldValue).divide(new BigDecimal(100));
                        accountService.specialAward(idss, percent, score, 1, inviteId, orderNo);
                    }
                }
                sktOrdersStores = sktOrdersStoresMapper.appFindOrderStoreById(orderNo);
                map2.put("orderNo",sktOrdersStores.getOrderNo());
                map2.put("payMoney",sktOrdersStores.getTotalMoney());
                map2.put("time",sktOrdersStores.getCheckTime());
                map2.put("mes","");
                return map2;
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                map2.put("mes","出错啦！");
                return map2;
            }
        }
	}

	@Override
	public Map<String, Object> apporderStore(Integer shopId, BigDecimal payMoney, Integer scoreRatio,Integer userId) {
		Map<String,Object> map = new HashMap<String,Object>();
		//		 用户在线下商城消费后申请积分
//		 验证商家存在和商家状态
		SktShops sktShops = sktShopsMapper.selectById(shopId);
		if(sktShops == null){
			map.put("mes","此商家不存在！");
			return map;
		}
		if(sktShops.getStoreStatus() == 0){
			map.put("mes","此用户线下商家已禁用！");
			return map;
		}
//		 查询出商家类型再检测每日店铺订单上限 铺的每日营业额是否超过上限
		//商家类型 0个体 1公司
		if(sktShops.getCompanyType() == 0) {
			//个体户每笔限额
			SktSysConfigs sktSysConfigs = sktSysConfigsMapper.selectSysConfigsByFieldCode("gthMBXE");
			String gthMBXE = sktSysConfigs.getFieldValue();
			if(payMoney.compareTo(new BigDecimal(gthMBXE)) == 1){
				map.put("mes","下单失败，您的订单金额大于商家每笔限额！");
				return map;
			}
			//个体户每日限额
			SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("gthMRXE");
			String gthMRXE = sktSysConfigs2.getFieldValue();
			Map<String,Object> map2 = new HashMap<String,Object>();
			map2.put("shopId",shopId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            map2.put("today",today);
            //查询商家的今日营业额
            BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map2);
            if(todayTurnover == null){
				todayTurnover = new BigDecimal(0);
			}
            if(todayTurnover.add(payMoney).compareTo(new BigDecimal(gthMRXE)) == 1){
                map.put("mes","对不起您的订单将让商家今天限额超过上限！");
                return map;
            }
		}
		if(sktShops.getCompanyType() == 1){
			//公司每笔限额
			SktSysConfigs sktSysConfigs = sktSysConfigsMapper.selectSysConfigsByFieldCode("qyMBXE");
			String qyMBXE = sktSysConfigs.getFieldValue();
            if(payMoney.compareTo(new BigDecimal(qyMBXE)) == 1){
                map.put("mes","下单失败，您的订单金额大于商家每笔限额！");
                return map;
            }
			//公司每日限额
			SktSysConfigs sktSysConfigs2 = sktSysConfigsMapper.selectSysConfigsByFieldCode("qyMRXE");
			String qyMRXE = sktSysConfigs2.getFieldValue();
            Map<String,Object> map2 = new HashMap<String,Object>();
            map2.put("shopId",shopId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            map2.put("today",today);
            //查询商家的今日营业额
            BigDecimal todayTurnover = sktOrdersStoresMapper.appFindTodayTurnover(map2);
            if(todayTurnover == null){
				todayTurnover = new BigDecimal(0);
			}
            if(todayTurnover.add(payMoney).compareTo(new BigDecimal(qyMRXE)) == 1){
                map.put("mes","对不起您的订单将让商家今天限额超过上限！");
                return map;
            }
		}
//		 再检测用户未支付订单的数量 消费者订单每人每天每店未支付订单2笔，每人每天未处理最多5笔
        //先查询在本店铺
        Map<String,Object> map2 = new HashMap<String,Object>();
		map2.put("shopId",shopId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());
        map2.put("today",today);
        map2.put("userId",userId);
        Integer notPayCountShop = sktOrdersStoresMapper.appFindNotPayOrders(map2);
        if(notPayCountShop == null){
			notPayCountShop = 0;
		}
        if(notPayCountShop >= 2){
            map.put("mes","对不起，您今日在本店铺未支付订单已达上线（2单），不能在此店铺下单了！");
            return map;
        }
        //查询用户今天所有未支付订单
        map2.put("shopId","");
        Integer notPayCountAll = sktOrdersStoresMapper.appFindNotPayOrders(map2);
        if(notPayCountAll == null){
			notPayCountAll = 0;
		}
        if(notPayCountShop >= 5){
            map.put("mes","对不起，您今日未支付订单已达上线（5单），不能再下单了！");
            return map;
        }
//		 再把申请积分的信息添加到orders_stores表
        SktOrdersStores sktOrdersStores = new SktOrdersStores();
        // 创建订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        sktOrdersStores.setOrderNo("1"+strDate+num);
        sktOrdersStores.setShopId(shopId);
        sktOrdersStores.setUserId(userId);
        sktOrdersStores.setOrderStatus(1);
        sktOrdersStores.setOrderType(2);
        sktOrdersStores.setTotalMoney(payMoney);
        sktOrdersStores.setScoreRatio(scoreRatio);
        sktOrdersStores.setScore(payMoney.multiply(new BigDecimal(scoreRatio)));
        sktOrdersStores.setOrderRemarks("线下消费，消费者主动下单");
        sktOrdersStores.setCreateTime(new Date());
        Integer insert = sktOrdersStoresMapper.insert(sktOrdersStores);
        if(insert != 0){
            map = sktOrdersStoresMapper.appFindOrderByid(sktOrdersStores.getOrderId());
//            map.put("orderNo",sktOrdersStores.getOrderNo());
//            map.put("payMoney",payMoney);
//            map.put("scoreRatio",scoreRatio);
//            map.put("score",sktOrdersStores.getScore());
//            map.put("orderStatus",sktOrdersStores.getOrderStatus());
            map.put("mes","");
            return map;
        }else{
            map.put("mes","出错啦！");
            return map;
        }
	}

	/**   插入积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	@Transactional
	public boolean insertLogScore(int fromId,int type, String orderNo,BigDecimal preScore,String remark,BigDecimal score,int scoreType,int userId){
		LogScore logScore=new LogScore();
		logScore.setCreateTime(new Date());
		logScore.setDataFlag(1);
		logScore.setFromId(fromId);
		logScore.setOrderNo(orderNo);
		logScore.setPreScore(preScore);
		logScore.setRemark(remark);
		logScore.setScore(score);
		logScore.setScoreType(scoreType);
		logScore.setType(type);
		logScore.setUserId(userId);
		Integer flag = logScoreMapper.insert(logScore);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	//添加库存记录
	@Transactional
	public Integer insertLogStockScore(Integer type,Integer fromId,Integer userId,String orderNo,BigDecimal preScore,Integer scoreType,BigDecimal score,String remark){
		LogStockscore logStockscore = new LogStockscore();
		logStockscore.setType(type);
		logStockscore.setFromId(fromId);
		logStockscore.setUserId(userId);
		// 生成订单号
//        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//        String strDate = sfDate.format(new Date());
//        String num = GetOrderNum.getRandom620(2);
		logStockscore.setOrderNo(orderNo);
		logStockscore.setPreScore(preScore);
		logStockscore.setScoreType(scoreType);
		logStockscore.setScore(score);
		logStockscore.setRemark(remark);
		logStockscore.setCreateTime(new Date());
		Integer insert = logStockscoreMapper.insert(logStockscore);
		return insert;
	}
}
